package Servlets;

import main.ServerGlobals;

import org.json.simple.JSONObject;

import pageProcessor.PageProcessorInterface;
import protocol.HTTPRequest;
import protocol.Headers;
import SQL.SQLLiteHandler;

public abstract class Servlet implements PageProcessorInterface {

	protected SQLLiteHandler fSQLLiteHandler;

	public Servlet() {
		fSQLLiteHandler = new SQLLiteHandler(WhatsAppConstatnts.DBNAME);
	}

	protected boolean areParametersRequiredSent(String[] parameters,
			HTTPRequest httpRequest) {
		JSONObject msgParams = httpRequest.getfHttpmsg().toJSONObject();
		boolean isValid = true;
		for (int i = 0; i < parameters.length; i++) {
			if (msgParams.get(parameters[i]) == null) {
				isValid = false;
			}
		}
		return isValid;
	}

	protected boolean isAuthorized(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		if (httpRequest.getfHTTPHttpRequestHeaders().getfCookies()
				.get(Headers.SESSIONID) == null
				|| !serverGlobals.sessionIdExists((String) httpRequest
						.getfHTTPHttpRequestHeaders().getfCookies()
						.get(Headers.SESSIONID))) {
			return false;
		}
		return true;
	}

	protected String getSessionId(HTTPRequest httpRequest) {
		return httpRequest.getfHTTPHttpRequestHeaders().getfCookies()
				.get(Headers.SESSIONID).toString();
	}

	protected boolean isCorrectMethod(HTTPRequest httpRequest, String method) {
		return (httpRequest.getfHTTPHttpRequestHeaders().getfMethod()
				.equals(method));
	}

}
